package cn.edu.scujj.view;

import cn.edu.scujj.dao.PurcharTongJiDao;
import cn.edu.scujj.bean.PurcharTongJi;
import cn.edu.scujj.utils.DButil;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

public class PurcharTongJiUI extends JFrame {

    private JScrollPane jScrollPane;
    private JTable table;
    private AbstractTableModel tableModel;
    private Vector<Vector<Object>> vector = new Vector<>();
    private PurcharTongJiDao dao = new PurcharTongJiDao();
    private JTextField txtName = new JTextField(15);
    private JTextField txtNum = new JTextField(10);
    private JTextField txtJinjia = new JTextField(10);
    private JTextField txtChushoujia = new JTextField(10);

    public PurcharTongJiUI() {
        initUI();
        initTable();
        initEvent();
        refreshData();
    }

    private void initUI() {
        setTitle("商品采购统计管理");
        setBounds(100, 100, 800, 600);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLayout(new BorderLayout(15, 15));
        setLocationRelativeTo(null);

        JPanel inputPanel = new JPanel(new FlowLayout(FlowLayout.LEADING, 10, 5));
        inputPanel.add(new JLabel("商品名称："));
        inputPanel.add(txtName);
        inputPanel.add(new JLabel("商品数量："));
        inputPanel.add(txtNum);
        inputPanel.add(new JLabel("进价："));
        inputPanel.add(txtJinjia);
        inputPanel.add(new JLabel("售价："));
        inputPanel.add(txtChushoujia);

        jScrollPane = new JScrollPane();
        table = new JTable();
        jScrollPane.setViewportView(table);

        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 5));
        JButton btnAdd = new JButton("添加");
        JButton btnDelete = new JButton("删除");
        JButton btnUpdate = new JButton("修改");
        JButton btnReset = new JButton("重置");
        JButton btnRefresh = new JButton("刷新");

        buttonPanel.add(btnAdd);
        buttonPanel.add(btnDelete);
        buttonPanel.add(btnUpdate);
        buttonPanel.add(btnReset);
        buttonPanel.add(btnRefresh);

        add(inputPanel, BorderLayout.NORTH);
        add(jScrollPane, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);
    }

    private void initTable() {
        String[] columnNames = {"商品名称", "商品数量", "进价", "出售价"};
        tableModel = new AbstractTableModel() {
            @Override
            public int getRowCount() {
                return vector.size();
            }

            @Override
            public int getColumnCount() {
                return columnNames.length;
            }

            @Override
            public String getColumnName(int column) {
                return columnNames[column];
            }

            @Override
            public Object getValueAt(int rowIndex, int columnIndex) {
                return vector.get(rowIndex).get(columnIndex);
            }
        };
        table.setModel(tableModel);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
    }

    private void initEvent() {
        table.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 1 && table.getSelectedRow() != -1) {
                    int row = table.getSelectedRow();
                    txtName.setText(vector.get(row).get(0).toString());
                    txtNum.setText(vector.get(row).get(1).toString());
                    txtJinjia.setText(vector.get(row).get(2).toString());
                    txtChushoujia.setText(vector.get(row).get(3).toString());
                }
            }
        });

        ActionListener listener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String cmd = e.getActionCommand();
                switch (cmd) {
                    case "添加":
                        addRecord();
                        break;
                    case "删除":
                        deleteRecord();
                        break;
                    case "重置":
                        resetFields();
                        break;
                    case "刷新":
                        refreshData();
                        break;
                }
            }
        };

        // 直接为按钮添加监听器（避免通过 getComponent 访问组件）
        JButton btnAdd = new JButton("添加");
        JButton btnDelete = new JButton("删除");
        JButton btnUpdate = new JButton("修改");
        JButton btnReset = new JButton("重置");
        JButton btnRefresh = new JButton("刷新");

        btnAdd.addActionListener(listener);
        btnDelete.addActionListener(listener);
        btnUpdate.addActionListener(listener);
        btnReset.addActionListener(listener);
        btnRefresh.addActionListener(listener);

        // 重新创建按钮面板并添加到窗口
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 5));
        buttonPanel.add(btnAdd);
        buttonPanel.add(btnDelete);
        buttonPanel.add(btnUpdate);
        buttonPanel.add(btnReset);
        buttonPanel.add(btnRefresh);
        add(buttonPanel, BorderLayout.SOUTH);
    }

    private void addRecord() {
        if (!validateInput()) return;

        PurcharTongJi tj = new PurcharTongJi();
        tj.setName(txtName.getText());
        tj.setNum(Double.parseDouble(txtNum.getText()));
        tj.setJinjia(Float.parseFloat(txtJinjia.getText()));
        tj.setChushoujia(Float.parseFloat(txtChushoujia.getText()));

        if (dao.addPurcharTongji(tj)) {
            JOptionPane.showMessageDialog(this, "添加成功", "操作提示", JOptionPane.INFORMATION_MESSAGE);
            resetFields();
            refreshData();
        } else {
            JOptionPane.showMessageDialog(this, "添加失败，请检查数据", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void updateRecord() {
        String name = txtName.getText();
        if (name.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请选择要修改的记录", "警告", JOptionPane.WARNING_MESSAGE);
            return;
        }

        if (!validateInput()) return;

        PurcharTongJi tj = new PurcharTongJi();
        tj.setName(name);
        tj.setNum(Double.parseDouble(txtNum.getText()));
        tj.setJinjia(Float.parseFloat(txtJinjia.getText()));
        tj.setChushoujia(Float.parseFloat(txtChushoujia.getText()));

        if (dao.updatePurcharTongji(tj)) {
            JOptionPane.showMessageDialog(this, "修改成功", "操作提示", JOptionPane.INFORMATION_MESSAGE);
            resetFields();
            refreshData();
        } else {
            JOptionPane.showMessageDialog(this, "修改失败，记录可能不存在", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void deleteRecord() {
        String name = txtName.getText();
        if (name.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请选择要删除的记录", "警告", JOptionPane.WARNING_MESSAGE);
            return;
        }

        if (dao.deletePurcharTongji(name)) {
            JOptionPane.showMessageDialog(this, "删除成功", "操作提示", JOptionPane.INFORMATION_MESSAGE);
            resetFields();
            refreshData();
        } else {
            JOptionPane.showMessageDialog(this, "删除失败，记录可能不存在", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private boolean validateInput() {
        try {
            if (txtName.getText().trim().isEmpty()) {
                throw new IllegalArgumentException("商品名称不能为空");
            }
            Double.parseDouble(txtNum.getText());
            Float.parseFloat(txtJinjia.getText());
            Float.parseFloat(txtChushoujia.getText());
            return true;
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this, "请输入正确格式的数字", "格式错误", JOptionPane.ERROR_MESSAGE);
            return false;
        } catch (IllegalArgumentException e) {
            JOptionPane.showMessageDialog(this, e.getMessage(), "输入错误", JOptionPane.WARNING_MESSAGE);
            return false;
        }
    }

    private void resetFields() {
        txtName.setText("");
        txtNum.setText("");
        txtJinjia.setText("");
        txtChushoujia.setText("");
    }

    private void refreshData() {
        vector.clear();
        try {
            // 调用 dao 的 findAll()，确保返回非空列表
            List<PurcharTongJi> list = dao.findAll();
            // 防御性代码：若 list 为 null（尽管 dao 应保证非空），则初始化为空列表
            if (list == null) {
                list = new ArrayList<>();
            }
            NumberFormat numFormat = NumberFormat.getInstance();
            NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();

            for (PurcharTongJi tj : list) {
                Vector<Object> row = new Vector<>();
                row.add(tj.getName());
                row.add(numFormat.format(tj.getNum()));
                row.add(currencyFormat.format(tj.getJinjia()));
                row.add(currencyFormat.format(tj.getChushoujia()));
                vector.add(row);
            }
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "数据加载失败", "错误", JOptionPane.ERROR_MESSAGE);
        }
        tableModel.fireTableDataChanged();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new PurcharTongJiUI().setVisible(true));
    }
}